<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 加载状态 -->
    <div v-if="loading" class="flex justify-center items-center min-h-screen">
      <div class="text-center">
        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        <p class="mt-2 text-gray-500">加载中...</p>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="flex justify-center items-center min-h-screen">
      <div class="text-center">
        <div class="mx-auto w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mb-4">
          <svg class="w-8 h-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
          </svg>
        </div>
        <h3 class="text-lg font-semibold text-gray-900 mb-2">加载失败</h3>
        <p class="text-gray-500 mb-4">{{ error }}</p>
        <button 
          @click="loadCourse"
          class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
        >
          重试
        </button>
      </div>
    </div>

    <!-- 主要内容 -->
    <div v-else-if="course" class="container mx-auto px-4 py-8">
      <!-- 返回按钮 -->
      <div class="mb-6">
        <button 
          @click="$router.go(-1)"
          class="flex items-center text-gray-600 hover:text-gray-800 transition-colors"
        >
          <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
          </svg>
          返回
        </button>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 左侧：课程信息 -->
        <div class="lg:col-span-2">
          <div class="bg-white rounded-lg shadow-sm p-8">
            <!-- 课程封面和基本信息 -->
            <div class="flex flex-col md:flex-row gap-6 mb-8">
              <div class="flex-shrink-0">
                <div class="w-48 h-64 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center relative overflow-hidden">
                  <img
                    v-if="course.thumbnail_url"
                    :src="course.thumbnail_url"
                    :alt="course.title"
                    class="absolute inset-0 w-full h-full object-cover"
                  />
                  <div v-else class="text-white text-center">
                    <svg class="w-16 h-16 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
                    </svg>
                    <span class="text-sm font-medium">{{ course.category }}</span>
                  </div>
                  
                  <!-- 视频播放图标 -->
                  <div v-if="course.video_url" class="absolute inset-0 bg-black/30 flex items-center justify-center">
                    <div class="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center backdrop-blur-sm">
                      <svg class="w-8 h-8 text-white ml-1" fill="currentColor" viewBox="0 0 24 24">
                        <path d="M8 5v14l11-7z"/>
                      </svg>
                    </div>
                  </div>
                </div>
              </div>

              <div class="flex-1">
                <h1 class="text-3xl font-bold text-gray-900 mb-4">{{ course.title }}</h1>
                
                <div class="flex flex-wrap gap-2 mb-4">
                  <span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm font-medium">
                    {{ course.category }}
                  </span>
                  <span class="px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm font-medium">
                    {{ getDifficultyName(course.difficulty) }}
                  </span>
                  <span class="px-3 py-1 bg-purple-100 text-purple-800 rounded-full text-sm font-medium">
                    {{ getTypeName(course.type) }}
                  </span>
                </div>

                <div class="text-gray-600 mb-4">
                  <p class="mb-2"><span class="font-medium">讲师：</span>{{ course.instructor }}</p>
                  <p class="mb-2"><span class="font-medium">时长：</span>{{ formatDuration(course.duration) }}</p>
                  <p class="mb-2"><span class="font-medium">语言：</span>{{ course.language || '中文' }}</p>
                  <p class="mb-2"><span class="font-medium">状态：</span>{{ getStatusName(course.status) }}</p>
                </div>

                <!-- 统计信息 -->
                <div class="flex items-center space-x-6 text-sm text-gray-500 mb-6">
                  <span class="flex items-center">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                    </svg>
                    {{ course.view_count }} 次浏览
                  </span>
                  <span class="flex items-center">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
                    </svg>
                    {{ course.like_count }} 次点赞
                  </span>
                  <span class="flex items-center">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>
                    </svg>
                    {{ course.enroll_count }} 人报名
                  </span>
                </div>

                <!-- 评分 -->
                <div v-if="course.rating" class="flex items-center mb-6">
                  <div class="flex items-center">
                    <div class="flex text-yellow-400">
                      <svg v-for="i in 5" :key="i" class="w-5 h-5" :class="i <= Math.round(course.rating) ? 'fill-current' : 'text-gray-300'" fill="currentColor" viewBox="0 0 24 24">
                        <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                      </svg>
                    </div>
                    <span class="ml-2 text-gray-600">{{ course.rating.toFixed(1) }} ({{ course.rating_count }} 人评价)</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 课程描述 -->
            <div class="mb-8">
              <h2 class="text-xl font-semibold text-gray-900 mb-4">课程简介</h2>
              <p class="text-gray-600 leading-relaxed">{{ course.description }}</p>
            </div>

            <!-- 课程内容 -->
            <div v-if="course.content" class="mb-8">
              <h2 class="text-xl font-semibold text-gray-900 mb-4">课程内容</h2>
              <div class="prose max-w-none">
                <div v-html="course.content"></div>
              </div>
            </div>

            <!-- 标签 -->
            <div v-if="course.tags && course.tags.length > 0" class="mb-8">
              <h2 class="text-xl font-semibold text-gray-900 mb-4">标签</h2>
              <div class="flex flex-wrap gap-2">
                <span
                  v-for="tag in course.tags"
                  :key="tag"
                  class="px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-sm"
                >
                  {{ tag }}
                </span>
              </div>
            </div>

            <!-- 视频播放器 -->
            <div v-if="course.video_url" class="mb-8">
              <h2 class="text-xl font-semibold text-gray-900 mb-4">课程视频</h2>
              <div class="aspect-video bg-gray-900 rounded-lg overflow-hidden">
                <iframe
                  v-if="getVideoEmbedURL(course)"
                  :src="getVideoEmbedURL(course)"
                  class="w-full h-full"
                  frameborder="0"
                  allowfullscreen
                ></iframe>
                <div v-else class="w-full h-full flex items-center justify-center text-white">
                  <p>无法加载视频</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：操作面板 -->
        <div class="lg:col-span-1">
          <div class="bg-white rounded-lg shadow-sm p-6 sticky top-8">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">操作</h3>
            
            <!-- 报名/继续学习按钮 -->
            <button
              @click="enrollCourse"
              :disabled="enrolling"
              class="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors mb-4"
            >
              {{ enrolling ? '处理中...' : (course.is_enrolled ? '继续学习' : '报名课程') }}
            </button>

            <!-- 收藏按钮 -->
            <button
              @click="toggleFavorite"
              :disabled="favoriting"
              class="w-full bg-gray-100 text-gray-700 py-3 px-4 rounded-lg hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors mb-4"
            >
              {{ favoriting ? '处理中...' : (course.is_favorited ? '取消收藏' : '收藏课程') }}
            </button>

            <!-- 下载资料按钮 -->
            <button
              v-if="(course as any).materials_url || (course as any).materials_path"
              @click="downloadMaterials"
              :disabled="downloading"
              class="w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors mb-4"
            >
              {{ downloading ? '下载中...' : '下载资料' }}
            </button>

            <!-- 分享 -->
            <div class="mb-4">
              <h4 class="text-sm font-medium text-gray-700 mb-2">分享</h4>
              <div class="flex space-x-2">
                <button
                  @click="shareToWechat"
                  class="flex-1 bg-green-500 text-white py-2 px-3 rounded text-sm hover:bg-green-600 transition-colors"
                >
                  微信
                </button>
                <button
                  @click="shareToWeibo"
                  class="flex-1 bg-red-500 text-white py-2 px-3 rounded text-sm hover:bg-red-600 transition-colors"
                >
                  微博
                </button>
                <button
                  @click="copyLink"
                  class="flex-1 bg-gray-500 text-white py-2 px-3 rounded text-sm hover:bg-gray-600 transition-colors"
                >
                  复制链接
                </button>
              </div>
            </div>

            <!-- 学习进度 -->
            <div v-if="course.is_enrolled" class="border-t border-gray-200 pt-4">
              <h4 class="text-sm font-medium text-gray-700 mb-2">学习进度</h4>
              <div class="mb-2">
                <div class="flex justify-between text-sm text-gray-600 mb-1">
                  <span>进度</span>
                  <span>{{ course.progress || 0 }}%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                  <div
                    class="bg-blue-600 h-2 rounded-full transition-all duration-300"
                    :style="{ width: `${course.progress || 0}%` }"
                  ></div>
                </div>
              </div>
              <div class="text-sm text-gray-500">
                <p v-if="(course as any).enrolled_at">报名时间：{{ formatDate((course as any).enrolled_at) }}</p>
                <p v-if="(course as any).last_watched_at">最后学习：{{ formatDate((course as any).last_watched_at) }}</p>
                <p v-if="(course as any).completed_at">完成时间：{{ formatDate((course as any).completed_at) }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { courseApi, type Course } from '@/api/course'

const route = useRoute()

// 响应式数据
const course = ref<Course | null>(null)
const loading = ref(false)
const error = ref('')
const enrolling = ref(false)
const favoriting = ref(false)
const downloading = ref(false)

// 方法
const loadCourse = async () => {
  try {
    loading.value = true
    error.value = ''
    
    const courseId = Number(route.params.id)
    const response = await courseApi.getCourse(courseId)
    course.value = response
  } catch (err: any) {
    error.value = err.message || '加载课程失败'
    console.error('加载课程失败:', err)
  } finally {
    loading.value = false
  }
}

const enrollCourse = async () => {
  if (!course.value) return
  
  try {
    enrolling.value = true
    await courseApi.enrollCourse({ course_id: course.value.id })
    course.value.is_enrolled = true
    course.value.enroll_count += 1
    alert('报名成功！')
  } catch (err: any) {
    console.error('报名失败:', err)
    alert(err.message || '报名失败')
  } finally {
    enrolling.value = false
  }
}

const toggleFavorite = async () => {
  if (!course.value) return
  
  try {
    favoriting.value = true
    await courseApi.toggleCourseFavorite(course.value.id)
    
    // 更新本地状态
    course.value.is_favorited = !course.value.is_favorited
    course.value.like_count += course.value.is_favorited ? 1 : -1
  } catch (err: any) {
    console.error('收藏失败:', err)
    alert(err.message || '操作失败')
  } finally {
    favoriting.value = false
  }
}

const downloadMaterials = async () => {
  if (!course.value) return
  
  try {
    downloading.value = true
    await courseApi.downloadCourseMaterials(course.value.id)
  } catch (err: any) {
    console.error('下载失败:', err)
    alert(err.message || '下载失败')
  } finally {
    downloading.value = false
  }
}

const getVideoEmbedURL = (course: Course): string => {
  return courseApi.getVideoEmbedURL(course)
}

const getTypeName = (type: string): string => {
  const typeMap: { [key: string]: string } = {
    video: '视频课程',
    document: '文档课程',
    mixed: '混合课程'
  }
  return typeMap[type] || type
}

const getDifficultyName = (difficulty: string): string => {
  const difficultyMap: { [key: string]: string } = {
    beginner: '初级',
    medium: '中级',
    advanced: '高级'
  }
  return difficultyMap[difficulty] || difficulty
}

const getStatusName = (status: string): string => {
  const statusMap: { [key: string]: string } = {
    published: '已发布',
    draft: '草稿',
    archived: '已归档'
  }
  return statusMap[status] || status
}

const formatDuration = (minutes: number): string => {
  if (minutes < 60) {
    return `${minutes}分钟`
  } else {
    const hours = Math.floor(minutes / 60)
    const mins = minutes % 60
    return mins > 0 ? `${hours}小时${mins}分钟` : `${hours}小时`
  }
}

const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const shareToWechat = () => {
  // 微信分享逻辑
  console.log('分享到微信')
}

const shareToWeibo = () => {
  // 微博分享逻辑
  console.log('分享到微博')
}

const copyLink = () => {
  navigator.clipboard.writeText(window.location.href)
  alert('链接已复制到剪贴板')
}

onMounted(() => {
  loadCourse()
})
</script>